﻿
namespace Leetcode.N0824;
public class Solution
{
    public string ToGoatLatin(string sentence)
    {

        var s = new System.Text.StringBuilder();
        var wordCount = 0;
        char? first = null;
        var hashset = new HashSet<char> { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

        void AppendWordEnd(char c)
        {
            wordCount++;
            if (first != null && first != '\0')
            {
                s.Append(first.Value);
            }
            s.Append("ma");

            for (int j = 0; j < wordCount; j++)
            {
                s.Append('a');
            }

            if (c != '\0')
            {
                s.Append(c);
            }
            first = null;
        }

        for (int i = 0; i < sentence.Length; i++)
        {
            var c = sentence[i];
            if (hashset.Contains(c))
            {
                if (first == null)
                {
                    first = '\0';
                }
                s.Append(c);
            }
            else if (c == ' ')
            {
                AppendWordEnd(c);
            }
            else
            {
                if (first == null)
                {
                    first = c;
                }
                else
                {
                    s.Append(c);
                }
            }

            if (i == sentence.Length - 1)
            {
                AppendWordEnd('\0');
            }
        }
        return s.ToString();
    }
}
